package com.js.basicutils.permission;

// Created by JS on 2021/1/16.

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.js.basicutils.R;
import com.js.basicutils.Utils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public final class PermissionActivity extends Activity {

    private static WeakReference<PermissionListener> permissionListener;
    private static WeakReference<String[]> permissions;

    public static void setPermissionListener(PermissionListener permissionListener) {
        if (permissionListener != null) {
            PermissionActivity.permissionListener = new WeakReference<>(permissionListener);
        }
    }

    public static void setPermissions(String[] permissions) {
        PermissionActivity.permissions = new WeakReference<>(permissions);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        requestPermissions(permissions.get(), Utils.getCodePermissionRequest());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Utils.getCodePermissionRequest()) {
            List<String> deniedPermissions = new ArrayList<>();
            boolean neverRequest = false;
            for (String permission : permissions) {
                neverRequest = ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, permission);
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permission);
                }
            }
            if (deniedPermissions.isEmpty()) {
                if (isListenerNotEmpty()) permissionListener.get().onGranted();
            } else {
                if (isListenerNotEmpty()) permissionListener.get().onDenied(deniedPermissions, neverRequest);
            }
            finish();
            overridePendingTransition(0, 0);
        }
    }

    private boolean isListenerNotEmpty() {
        return permissionListener != null && permissionListener.get() != null;
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        permissionListener = null;
        permissions = null;
        super.onDestroy();
    }
}
